package com.example.result

import android.app.SearchManager
import android.content.SearchRecentSuggestionsProvider
import android.database.Cursor
import android.database.MatrixCursor
import android.net.Uri
import android.provider.BaseColumns
import android.text.TextUtils
import android.util.Log
import com.lly.tboc.zhouyi.db.ZhouyiDb
import dagger.hilt.android.EntryPointAccessors

class MySuggestionProvider : SearchRecentSuggestionsProvider() {
    lateinit var zhouyiDb: ZhouyiDb

    init {
        setupSuggestions(AUTHORITY, MODE)

    }

    override fun onCreate(): Boolean {
        val appContext = context?.applicationContext ?: throw IllegalStateException()

        zhouyiDb = EntryPointAccessors.fromApplication(appContext, ProviderEntryPoint::class.java)
            .zhouyiDb()
        return super.onCreate()
    }

    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): Cursor? {
        if (TextUtils.isEmpty(selectionArgs?.get(0))) {
            return super.query(uri, projection, selection, selectionArgs, sortOrder)
        } else {
            selectionArgs?.mapIndexed { index, s ->
                Log.d("search", "$index $s")
            }
            Log.d(
                "search",
                "$selection"
            )
            val cursor = MatrixCursor(
                arrayOf(
                    BaseColumns._ID,
                    SearchManager.SUGGEST_COLUMN_TEXT_1,
                    SearchManager.SUGGEST_COLUMN_TEXT_2,
                    SearchManager.SUGGEST_COLUMN_QUERY
                )
            )
            val yaoList = zhouyiDb.searchDao().searchYaoByLike("%${selectionArgs?.get(0)}%")
            yaoList.mapIndexed { index, yao ->
                cursor.addRow(arrayListOf(index, yao.ci, yao.xiang, yao.name))
            }
            return cursor
        }
    }

    companion object {
        const val AUTHORITY = "com.example.result.MySuggestionProvider"
//        const val MODE: Int =

        const val MODE: Int =
            SearchRecentSuggestionsProvider.DATABASE_MODE_QUERIES or SearchRecentSuggestionsProvider.DATABASE_MODE_2LINES
    }
}